import re
from django.contrib.auth.backends import ModelBackend
from users.models import User
# user=None
# 只要你采用了jwt的认证,登录成功之后,会调用此方法,此方法就把认证的用户信息,传递过来了



def jwt_response_payload_handler(token, user=None, request=None):

    return {
        'token': token,
        'user_id':user.id,
        'username':user.username
    }


# 增加用户名和手机号作为用户认证登录：Django系统authentication()默认的是验证用户名和密码是否正确
# 我们需要加入手机号验证，重写系统的authentication()函数
# 需求分析：得到手机号或用户名，查询用户信息，然后调用加密方法查看密码是否正确

# 查询用户信息
def get_user_by_account(account):
    # 判断是否符合手机号格式
    if re.match(r'^1[345789]\d{9}',account):
        user = User.objects.get(mobile=account)
    else:
        user = User.objects.get(username=account)
    return user


class UsernameMobileAuthbackend(ModelBackend):

    def authenticate(self, request, username=None, password=None, **kwargs):
        user = get_user_by_account(username)
        if user is not None and user.check_password(password):
            return user
        return None


class SettingsBackend(object):
    """
    Authenticate against the settings ADMIN_LOGIN and ADMIN_PASSWORD.

    Use the login name and a hash of the password. For example:

    ADMIN_LOGIN = 'admin'
    ADMIN_PASSWORD = 'pbkdf2_sha256$30000$Vo0VlMnkR4Bk$qEvtdyZRWTcOsCnI/oQ7fVOu1XAURIZYoOZ3iq8Dr4M='
    """

    def authenticate(self, request, username=None, password=None):
       user = get_user_by_account(username)
       if user is not None and user.check_password(password):
           return user
       return None

    # 继承自object 的类需要多实现一个方法get_user(self,user_id)
    def get_user(self, user_id):
        try:
            return User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return None